package com.example.threadstack;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.example.threadstack.Utils.getCurrentTime;

@RestController
@RequestMapping("high-cpu")
public class HighCPUController {
    private ExecutorService executorService = Executors.newFixedThreadPool(1, new BasicThreadFactory
            .Builder()
            .namingPattern("High-CPU-%d")
            .build()
    );

    @RequestMapping("/{loop}")
    public DeferredResult<String> highCpu(@PathVariable long loop){
        DeferredResult<String> result = new DeferredResult<>(10 * 1000L, "TimeOut");
        CompletableFuture.supplyAsync(()->{
            for (int i=0;i<loop;i++){
                try {
                    Math.cos(i + 10);
                }catch (Exception e){

                }
//                Thread.yield();
            }
            return getCurrentTime();
        }, executorService).thenAccept(r->result.setResult(r));

        return result;
    }
}
